public class ConvertToStudentAccount 
{
    //Variable Declaration
    public string LeadId {get; set;}
    public string AccountId{get; set;}
    public string soqlFormationText {get;set;}
    public string a {get;set;}
    public string leadSOQL {get;set;}
    public Lead leadRecord {get;set;}
    public integer totalDupCount {get;set;}
    public Opportunity opps {get; set;}
    public Account accts {get; set;}
    public integer countDuplicateCondition1 {get; set;}
    public integer countDuplicateCondition2 {get; set;}
    public integer countDuplicateCondition3 {get; set;}
    public string isdebug {get; set;}
    public string accid {get; set;}
    public string succss {get; set;} 
    public string test {get; set;}

    //Declaration of Options that are selected during the lead conversion process
    public pageReference KeepStudentData()
    {
        PageReference pr;
        return pr;
    }
    public pageReference KeepLeadData()
    {
        PageReference pr;
        return pr;
    }
    public pageReference ForceCreateOppty()
    {
        PageReference pr;
        return pr;
    }
    public ConvertToStudentAccount(ApexPages.StandardController controller) 
    {
         LeadId = ApexPages.currentPage().getParameters().get('leadId');    
         System.debug('----------------->>>>>>>>> '+ LeadId);      
    }
    /*
    Main Method that checks for duplicates and Converts Lead to Account
    */
    public pageReference convertLead() 
    {
           
        PageReference pr;
        //string leadID = LeadId ;
        List <string> leadFieldMap = getoDescribe('Lead');
        // build dynamic lead select statement
        soqlFormationText ='Id, ' ;
          
        integer leadFieldCount =0;

        //Dynamic Formation of Lead Fields and Passing it to the SOQL Query
        /*
        for (String lfm: leadFieldMap)
        {
             leadFieldCount ++;
             if(leadFieldCount >1){soqlFormationText +=', ';}
             soqlFormationText += lfm; 
        }
        
        leadSOQL = 'SELECT '+soqlFormationText +' , Name FROM Lead WHERE Id =\''+LeadId +'\' LIMIT 1';*/  
        leadSOQL = 'SELECT email,Phone,firstname,lastname,Birth_Date__c , Name FROM Lead WHERE Id =\''+LeadId +'\' LIMIT 1';      
        system.debug('leadSOQL-->');
        system.debug(leadSOQL);
        system.debug('leadSOQL-->');
        leadRecord = Database.query(leadSOQL);

        //Duplicate Check Identifiers
        List<Account> dupAccountsCase1;
        List<Account> dupAccountsCase2;        
        List<Account> dupAccountsCase3;
        countDuplicateCondition1 =0;
        countDuplicateCondition2 =0;
        countDuplicateCondition3 =0;
        

        /* Logic for the Below conditions statements
        1. Check 
            if the Lead Email is not null 
                Then check for the Duplicate  based on firstname lastname and email. If exist Present the Lead Conversion Options Screen
                If no duplicate then Check if the PHONE is not null
                    Then Check for the Duplicate based on firstname lastname and phone. If exist Present the Lead Conversion Options Screen
                    if no duplicate then check if the birthdate is not null
                        Then Check for the Duplicate based on firstname lastname and birthdate. If exist Present the Lead Conversion Options Screen
                    else
                        Present the lead conversion options screen
                else
                    Present the lead conversion options screen
            else
               Check if the PHONE Is not nll
                       Then Check for the Duplicate based on firstname lastname and phone. If exist Present the Lead Conversion Options Screen
                    if no duplicate then check if the birthdate is not null
                        Then Check for the Duplicate based on firstname lastname and birthdate. If exist Present the Lead Conversion Options Screen
                    else
                        Present the lead conversion options screen
                else
                    check if the birthdate is not null
                        Then Check for the Duplicate based on firstname lastname and birthdate. If exist Present the Lead Conversion Options Screen
                    else
                        Convert Lead as there are no duplicates
        */ 
        if(String.valueOf(leadRecord.email) != null)
        {                
            // Match on First Name, Last Name, AND any emaileadRecord.
            countDuplicateCondition1 = [SELECT count() FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND personEmail = :leadRecord.email ]; 
            if(countDuplicateCondition1 >0)
            {
                dupAccountsCase1 = [SELECT ID FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND personEmail = :leadRecord.email ]; 
            }
            else
            {
                
                  if(String.valueOf(leadRecord.Phone)!= null)
                  {                      
                    // Match on First Name, Last Name, AND mobile or home phone number.
                    countDuplicateCondition2 = [SELECT count() FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND (PersonMobilePhone = :leadRecord.Phone OR  PersonHomePhone = :leadRecord.Phone OR PersonOtherPhone= :leadRecord.Phone OR Phone = :leadRecord.Phone)];
                    if(countDuplicateCondition2 > 0)
                    {
                        dupAccountsCase2 = [SELECT ID FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND (PersonMobilePhone = :leadRecord.Phone OR  PersonHomePhone = :leadRecord.Phone OR PersonOtherPhone= :leadRecord.Phone OR Phone = :leadRecord.Phone)]; 
                    }
                    else
                    {
                        if(String.valueOf(leadRecord.Birth_Date__c) != null)
                        {
                                // Match on First Name, Last Name, AND Birthdate.
                            countDuplicateCondition3 = [SELECT count() FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND PersonBirthdate = :leadRecord.Birth_Date__c ];
                            if(countDuplicateCondition3 >0)
                            {
                                dupAccountsCase3 = [SELECT ID,personcontactId FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND PersonBirthdate = :leadRecord.Birth_Date__c ];
                            }
                        }
                        
                    }
                 }
                 else
                 {
                    if(String.valueOf(leadRecord.Birth_Date__c) != null)
                    {
                            // Match on First Name, Last Name, AND Birthdate.
                        countDuplicateCondition3 = [SELECT count() FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND PersonBirthdate = :leadRecord.Birth_Date__c ];
                        if(countDuplicateCondition3 >0)
                        {
                            dupAccountsCase3 = [SELECT ID,personcontactId FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND PersonBirthdate = :leadRecord.Birth_Date__c ];
                        }
                    }
                }                  
            }
        }
        else
        {
            if(String.valueOf(leadRecord.Phone)!= null)
            {
                // Match on First Name, Last Name, AND mobile or home phone number.
                countDuplicateCondition2 = [SELECT count() FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND (PersonMobilePhone = :leadRecord.Phone OR  PersonHomePhone = :leadRecord.Phone OR PersonOtherPhone= :leadRecord.Phone OR Phone = :leadRecord.Phone)];
                if(countDuplicateCondition2 > 0)
                {
                    dupAccountsCase2 = [SELECT ID FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND (PersonMobilePhone = :leadRecord.Phone OR  PersonHomePhone = :leadRecord.Phone OR PersonOtherPhone= :leadRecord.Phone OR Phone = :leadRecord.Phone)]; 
                }
                else
                {
                    if(String.valueOf(leadRecord.Birth_Date__c) != null)
                    {
                            // Match on First Name, Last Name, AND Birthdate.
                        countDuplicateCondition3 = [SELECT count() FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND PersonBirthdate = :leadRecord.Birth_Date__c ];
                              //                      System.debug('countDuplicateCondition3' + countDuplicateCondition3 );
                        if(countDuplicateCondition3 >0)
                        {
                            dupAccountsCase3 = [SELECT ID,personcontactId FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND PersonBirthdate = :leadRecord.Birth_Date__c ];
                        }
                                    //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'----Is countDuplicateCondition3 ?-->'));  
                    }
                        
                 }                  
            }
            else
            {
                if(String.valueOf(leadRecord.Birth_Date__c) != null)
                {
                    // Match on First Name, Last Name, AND Birthdate.                    
                    countDuplicateCondition3 = [SELECT count() FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND PersonBirthdate = :leadRecord.Birth_Date__c ];
                    if(countDuplicateCondition3 >0)
                    {
                        dupAccountsCase3 = [SELECT ID FROM ACCOUNT WHERE firstname like :leadRecord.firstname AND lastname like :leadRecord.lastname AND PersonBirthdate = :leadRecord.Birth_Date__c ];
                    }
                }
            }
        }
        
        totalDupCount = countDuplicateCondition1 + countDuplicateCondition2 + countDuplicateCondition3 ;
        //This conditional statement means no dup count so Convert Lead
        System.debug('-------------191');
        if(totalDupCount == 0)
        {
            database.LeadConvert convertLead= new database.LeadConvert();
            convertLead.setLeadId(LeadId);
            LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
            convertLead.setConvertedStatus(convertStatus.MasterLabel);
            try {Database.LeadConvertResult convertedResult= Database.convertLead(convertLead);}
            catch(Exception e){ 
            ApexPages.addMessages(e);
            return null;
            }
            Lead ConvertedLead = [SELECT Name, Id, IsConverted, ConvertedDate, ConvertedAccountId, ConvertedContactId, ConvertedOpportunityId FROM Lead WHERE IsConverted = True AND Id =:LeadId limit 1 ];
            
            //Commented out by Rex 3/4 based on conversation with Sri
            //ConvertedLead.ConvertedAccountId = 'wewewewe';
            
            String ConvertedAccountId = ConvertedLead.ConvertedAccountId;
            
            String ConvertedOpportunityId = ConvertedLead.ConvertedOpportunityId;
            
            System.debug('--------------------- 213 '+ConvertedAccountId +' --- '+ ConvertedOpportunityId);
            Opportunity opportunity;
            Account ac;
            if(account.ID != null)
            {
                ac = [ Select Id,   CEL_Assigned__c, CEL_Assigned_Date__c, CEL_Assigned_Legacy__c from Account where id =:ConvertedAccountId];
            }
            opportunity= new Opportunity(accountId=ConvertedAccountId, CEL_Assigned__c = ac.CEL_Assigned__c,CEL_Assigned_Date__c = ac.CEL_Assigned_Date__c, CEL_Assigned_Legacy__c = ac.CEL_Assigned_Legacy__c,id = ConvertedOpportunityId);
            
            if(opportunity.id != null)
            {
                update opportunity;
            }
            
            String ConvertedContactId = ConvertedLead.ConvertedContactId;
            //This method is used to updateall the custom fields in account,Contact,oppty
            UpdateLeadData(LeadId,ConvertedAccountId,ConvertedOpportunityId);
            
            String newPageUrl = '/'+ConvertedAccountId ;
            pr = new PageReference(newPageUrl);
            pr.setRedirect(true);
        }
        //This conditional statement means 1 dup count exists in one amoung the 3 Email,Phone,BirthDate scenarios so Present the Lead Conversion Options screen
        if(totalDupCount == 1)        
        {
            String newPageUrl;
            if(countDuplicateCondition1 >0)
            {
                newPageUrl = '/apex/LeadConversionOptions?leadID='+LeadId +'&act_id='+string.Valueof(dupAccountsCase1[0].id);
            }
            if(countDuplicateCondition2 >0)
            {
                newPageUrl = '/apex/LeadConversionOptions?leadID='+LeadId +'&act_id='+string.Valueof(dupAccountsCase2[0].id);
            }
            if(countDuplicateCondition3 >0)
            {               
                newPageUrl = '/apex/LeadConversionOptions?leadID='+LeadId +'&act_id='+string.Valueof(dupAccountsCase3[0].id);
            }
            pr = new PageReference(newPageUrl);
            pr.setRedirect(true);
        }
        //This condition is for more duplicates present then the user  may have to go back and correct it before converting the lead.
        if(totalDupCount > 1)        
        {
           ApexPages.Message erMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'There are multiple duplicate Accounts with this Lead criteria. Please merge the accounts before converting the Lead.');
           ApexPages.addMessage(erMsg);       
        }
        return  pr;
    }
    
    
    public void UpdateLeadData(string leadID,string accountID,string opptyID)
    {
    
        List <string> leadFields = getoDescribe('Lead');
        string soqlLDFormationText ='Id, ' ;
        integer ldFieldCount =0;

        for (String lfm: leadFields)
        {
             ldFieldCount ++;
             if(ldFieldCount >1){soqlLDFormationText +=', ';}
             soqlLDFormationText += lfm; 
        }

        string ldSOQL = 'SELECT '+soqlLDFormationText +' FROM Lead WHERE Id = \''+leadID+'\' LIMIT 1';        
        Lead lead= Database.query(ldSOQL);

        List <string> accountFields = getoDescribe('account');
        string soqlAccountFormationText ='Id,' ;
        integer accountFC =0;
        
        //Declaration of variables to add Account fields into map
        Map<string, string> AccountFieldsMap = new Map<string, string> {};
        string removedActPerson;
        string removedActpc;
        string removedActc;
        string removedActUnderscore;
        //end declaration
        
        for (String afm: accountFields)
        {
             accountFC ++;
             if(!soqlAccountFormationText.contains('jigsaw'))
             {
                 if(accountFC >1){soqlAccountFormationText +=', ';}
                 soqlAccountFormationText += afm; 
             }
             
            //Parse Account field names and add to map to compare against Lead field names
            removedActPerson= afm.toLowerCase().replace('person','');
            removedActpc= removedActPerson.replace('__pc','');
            removedActc= removedActpc.replace('__c','');
            removedActUnderscore= removedActc.replace('_','');
            AccountFieldsMap.put(removedActUnderscore,afm);
            //end parse
        }
        
        /*
        //debug code check
        for (String fieldName : AccountFieldsMap.keySet()){
            System.debug('field name is ' + fieldName + ',field value is ' + AccountFieldsMap.get(fieldname));
        }
        //end debug
        */
        
        string actSOQL = 'SELECT IsPersonAccount,'+soqlAccountFormationText +'  FROM account WHERE Id = \''+accountID+'\' LIMIT 1';        
        
        account account= Database.query(actSOQL );
        
        List <string> opptyFields = getoDescribe('opportunity');
        string soqlOpptyFormationText ='Id, ' ;
        integer opptyFC =0;
        
        //Declaration of variables to add Opportunity fields into map
        Map<string, string> OpptyFieldsMap = new Map<string, string> {};
        string removedOpptyc;
        string removedOpptyUnderscore;
        //end declaration
        
        for (String ofm: opptyFields )
        {
             opptyFC ++;
             if(opptyFC >1){soqlOpptyFormationText +=', ';}
             soqlOpptyFormationText += ofm;
             
             //Parse Opportunity field names and add to map to compare against Lead field names
             removedOpptyc= ofm.toLowerCase().replace('__c','');
             removedOpptyUnderscore= removedOpptyc.replace('_','');
             OpptyFieldsMap.put(removedOpptyUnderscore,ofm);
             //end parse 
        }

       string  opptySOQL = 'SELECT '+soqlOpptyFormationText +'  FROM opportunity WHERE Id = \''+opptyID+'\' LIMIT 1';        
        Opportunity oppty = Database.query(opptySOQL);
        
        
    
        //Lead lead=[SELECT Employer_Text__c,Referred_By_Name__c,Hot_Transfer_Date__c,Priority_Note__c,Age__c, AnnualRevenue, Anticipated_Start_Date__c,Employer_Text__c, Birth_Date__c, CEL_Assigned__c, CEL_Assigned_Date__c, CEL_Assigned_Legacy__c, Campus__c, Campus_Text__c, City, College_credits_outside_US__c, Company, IsConverted, ConvertedAccountID__c, ConvertedAccountId, ConvertedContactId, ConvertedDate, ConvertedDate__c, ConvertedOpportunityId__c, ConvertedOpportunityId, Country, Country_of_Birth__c, Country_of_Birth_Text__c, Country_of_Residence__c, Country_of_Residence_Text__c, CreatedById, CreatedDate, Credit_Level__c, Data_Mapping_Status__c, Date_Appointment__c, IsDeleted, Description, DoNotCall, Do_Not_Text_Message__c, Document_Storage_URL__c, Duplicate_Account__c, Duplicate_Lead__c, Email, EmailBouncedDate, EmailBouncedReason, HasOptedOutOfEmail, NumberOfEmployees, Employer__c, External_ID_1__c, External_ID_2__c, Fax, FirstName, Foreign_Credit__c, Name, Gender__c, Generic_Phone__c, Highest_Level_of_Education__c, Home_Phone__c, IRN__c, Industry, IsConverted__c, LastActivityDate, LastModifiedById, LastModifiedDate, LastName, Lead_Assigned_Date__c, Id, Lead_ID__c, LeadSource, Lead_Source_2__c, Lead_Source_Detail__c, Lead_Source_Detail_2__c, Marketing_Email__c, Marketing_Phone__c, MasterRecordId, Middle_Name__c, Military_Base__c, Military_Branch__c, Military_End_Date__c, Military_Rank__c, Military_Start_Date__c, Military_Status__c, Military_TDY__c, MobilePhone, Mode__c, Mode_Text__c, Other_Email__c, Other_Email_2__c, Other_Email_2_Description__c, Other_Email_Description__c, Other_Phone__c, Other_Phone_2__c, Other_Phone_2_Description__c, Other_Phone_Description__c, OwnerId, Personal_Email__c, Phone, Preferred_Email__c, Preferred_First_Name__c, Preferred_Phone__c, Previous_Last_Name__c, Primary_Payment_Option__c, Priority__c, Program__c, Program_Text__c, RecordTypeId, Salutation, Secondary_Payment_Option__c, State__c, State_Province__c, State, Status, Status_Detail__c, Street, SystemModstamp, Title, University_Email__c, IsUnreadByOwner, Website, Work_Email__c, Work_Phone__c, You_may_call_or_email_me__c, PostalCode, Date_Contacted__c, Date_Declined__c, Date_No_Further_Action__c FROM Lead where Id= :leadID];        
        //Account account=[SELECT  Employer_Text__pc,Description, Fax, Account_ID__c, Id, Name, Phone, Rating, Site, Type, Age__pc, AnnualRevenue, PersonAssistantName, PersonAssistantPhone, BillingCity, BillingCountry, BillingState, BillingStreet, BillingPostalCode, PersonBirthdate, CEL_Assigned__c, CEL_Assigned_Date__c, CEL_Assigned_Legacy__c, PersonContactId, Country_of_Birth__pc, Country_of_Residence__pc, CreatedById, CreatedDate, Credit_Level__pc, IsDeleted, PersonDepartment, PersonDoNotCall, Do_Not_Text_Message__pc, Document_Storage_URL__c, PersonEmail, PersonEmailBouncedDate, PersonEmailBouncedReason, PersonHasOptedOutOfEmail, NumberOfEmployees, Employer__pc, External_ID_1__c, External_ID_2__c, PersonHasOptedOutOfFax, FirstName, Foreign_Credit__pc, Gender__pc, PersonHomePhone, IRN__c, Industry, IsPersonAccount, LastActivityDate, LastModifiedById, LastModifiedDate, LastName, PersonLastCURequestDate, PersonLastCUUpdateDate, PersonLeadSource, Lead_Source_2__pc, Lead_Source_Detail__pc, PersonMailingCity, PersonMailingCountry, PersonMailingState, PersonMailingStreet, PersonMailingPostalCode, Marketing_Email__pc, Marketing_Phone__pc, MasterRecordId, Middle_Name__pc, Military_Base__pc, Military_Branch__pc, Military_End_Date__pc, Military_Rank__pc, Military_Start_Date__pc, Military_Status__pc, Military_TDY__pc, PersonMobilePhone, Opportunity_Applications_Accepted__c, Opportunity_Applications_in_Progress__c, PersonOtherCity, PersonOtherCountry, Other_Email__pc, Other_Email_2__pc, Other_Email_2_Description__pc, Other_Email_Description__pc, PersonOtherPhone, Other_Phone_2__pc, Other_Phone_2_Description__pc, Other_Phone_Description__pc, PersonOtherState, PersonOtherStreet, PersonOtherPostalCode, OwnerId, ParentId, Passport_Country_of_Issue__pc, Passport_Exp_Date__pc, Passport_Issue_Date__pc, Passport_Number__pc, Person_Account_Contact_ID__c, Personal_Email__pc, Personal_Information__pc, Preferred_Email__pc, Preferred_First_Name__pc, Preferred_Phone__pc, Previous_Last_Name__pc, Primary_Nationality__pc, RecordTypeId, Salutation, Secondary_Nationality__pc, ShippingCity, ShippingCountry, ShippingState, ShippingStreet, ShippingPostalCode, Status__c, SystemModstamp, PersonTitle, University_Email__pc, Website, Work_Email__pc, Work_Phone__pc, Lead_Source_Detail_2__pc, Opportunities_Alumni__c, Opportunities_Maintenance__c, Opportunities_No_Further_Action__c FROM Account where Id=:accountID];
        /*Opportunity oppty=[SELECT Referred_By_Name__c ,Hot_Transfer_Date__c,Hot_Transfer__c ,AccountId, Amount, Anticipated_Start_Date__c, Application_ID__c, CEL_Assigned__c, CEL_Assigned_Date__c, CEL_Assigned_Legacy__c, CampaignId, Campus__c, CloseDate, IsClosed, CreatedById, CreatedDate, Date_Application_Started__c, Date_Application_Submitted__c, Date_Appointment__c, Date_Contacted__c, Date_Declined__c, Date_Dropped__c, Date_Eligible_to_Register__c, Date_Exited__c, Date_Graduated__c, Date_No_Further_Action__c, Date_Registered__c, Date_Started_Status__c, Date_Submitted_for_Review__c, IsDeleted, Description, External_ID_1__c, External_ID_2__c, ForecastCategoryName, ForecastCategory, HasOpportunityLineItem, Interest_ID__c, LastActivityDate, LastModifiedById, LastModifiedDate, LeadSource, Lead_Source_2__c, Lead_Source_2_Detail__c, Lead_Source_Detail__c, Mode__c, Motivation_Score__c, Name, NextStep, Opportunity_Assigned_Date__c, Id, Type, OwnerId, Pricebook2Id, Primary_Payment_Option__c, Priority__c, Program__c, RecordTypeId, Secondary_Payment_Option__c, Start_Date__c, StageName, Status_Detail__c, SystemModstamp, IsWon FROM Opportunity where id=:opptyID];
        */
//Account account=[SELECT  IsPersonAccount, Id, PersonAssistantName, Lead_Source_Detail_2__pc,PersonContactId,  PersonHasOptedOutOfEmail, ParentId, Lead_Source_Detail__pc, External_ID_2__c, BillingCity, University_Email__pc, RecordTypeId, PersonLeadSource, Industry, Country_of_Residence__pc, PersonDoNotCall, PersonTitle, Work_Phone__pc, Document_Storage_URL__c, Previous_Last_Name__pc, Other_Email_Description__pc, AnnualRevenue, OwnerId, Other_Phone_2_Description__pc, PersonDepartment, PersonMailingCity, Military_End_Date__pc, Personal_Email__pc, NumberOfEmployees, Foreign_Credit__pc, Credit_Level__pc, ShippingPostalCode, Account_ID__c, Military_Branch__pc, Military_Start_Date__pc, BillingState, LastName, Military_Rank__pc, Lead_Source_2__pc, CEL_Assigned__c, PersonOtherPostalCode, PersonOtherState, Other_Phone_2__pc, ShippingStreet, Passport_Country_of_Issue__pc, Site, Person_Account_Contact_ID__c, PersonMailingCountry, PersonOtherCity, ShippingCountry, FirstName, Primary_Nationality__pc, CEL_Assigned_Date__c, Preferred_Phone__pc, Priority_Note__pc, Salutation, PersonOtherCountry, Gender__pc, Phone, Status__c, PersonOtherStreet, PersonHasOptedOutOfFax, External_ID_1__c, Other_Email_2__pc, Type, PersonMobilePhone, PersonOtherPhone, Description, Military_Base__pc, Account_Assigned_Date__c, Fax, PersonEmailBouncedDate, ShippingCity, PersonMailingStreet, BillingPostalCode, ShippingState, Other_Email_2_Description__pc, Passport_Number__pc, Employer__pc, Preferred_Email__pc, Employer_Text__pc, Secondary_Nationality__pc, Military_Status__pc, PersonMailingState, Passport_Issue_Date__pc, PersonEmail, Country_of_Birth__pc, Military_TDY__pc, BillingCountry, PersonBirthdate, Passport_Exp_Date__pc, CEL_Assigned_Legacy__c, Do_Not_Text_Message__pc, Preferred_First_Name__pc, Work_Email__pc, Name, Marketing_Phone__pc, Middle_Name__pc, Website, PersonAssistantPhone, Personal_Information__pc, PersonHomePhone, BillingStreet, Marketing_Email__pc, PersonEmailBouncedReason, Other_Phone_Description__pc, Rating, Other_Email__pc, PersonMailingPostalCode  FROM account WHERE Id=:accountID];

        // build dynamic lead select statement
       // get a dynamic list of object fields for matching and converting
        List <string> leadfieldMap = getoDescribe('Lead');               
        List <string> opptyfieldMap = getoDescribe('Opportunity');   
    
        string removedLeadc;
        string removedLeadUnderscore;
            
        Map<string, string> LeadAccountMap = new Map<string, string> {};
        Map<string, string> LeadOpptyMap = new Map<string, string> {};

        integer cnt=0;
        integer actCnt=0;
        integer opptyCnt=0;
        List<string> newAccountList=new List<string>();
        
        for (cnt=0;cnt<leadfieldMap.size();cnt++) 
         {
            removedLeadc='';
            removedLeadUnderscore='';
            
            // default address is PersonMailing
            removedLeadc= leadfieldMap[cnt].toLowerCase().replace('__c','');
            removedLeadUnderscore= removedLeadc.replace('_','');   
            actCnt=0;
            opptyCnt=0;
            
            //Compare Account fields with Lead fields; if match, add to Lead/Account map for later use
            if((AccountFieldsMap.containsKey(removedLeadUnderscore)) && (leadfieldMap[cnt]!='RecordTypeId') && (leadfieldMap[cnt] !='Name'))
                {           
                    LeadAccountMap.put(AccountFieldsMap.get(removedLeadUnderscore),leadfieldMap[cnt]);
                }
            //END compare

            //Compare Opportunity fields with Lead fields; if match, add to Lead/Opportunity map for later use
            if((OpptyFieldsMap.containsKey(removedLeadUnderscore)) && (leadfieldMap[cnt]!='RecordTypeId') && (leadfieldMap[cnt] !='Name'))
                {           
                    LeadOpptyMap.put(OpptyFieldsMap.get(removedLeadUnderscore),leadfieldMap[cnt]);
                }
            //END compare

        }
        
            for(String s:LeadAccountMap.KeySet())
            {     
                if(account.get(s)==null && lead.get(LeadAccountMap.get(s))!=null)
                {
                    account.put(s,lead.get(LeadAccountMap.get(s)));            
                }
            }
            
            try
            {
                Database.SaveResult SR = database.update(account);
                //for(Database.Error err: SR.getErrors())
                //{
                    //system.debug('Error --> ' + err);
                    //system.debug('Error getMessage --> ' + err.getMessage());
                    //system.debug('Error getStatusCode--> ' + err.getStatusCode());
                   // process any errors here 
            
                //}
            }
            catch(DMLException e)
            {
                 //ApexPages.addMessage(e);
            }
            
            for(String o:LeadOpptyMap.KeySet())
            {     
                if(oppty.get(o)==null && lead.get(LeadOpptyMap.get(o))!=null)
                {
                    if((o!=null)&&(LeadAccountMap.get(o)!=null))
                    {
                        if(lead.get(LeadAccountMap.get(o))!=null)
                        {
                            oppty.put(o,lead.get(LeadAccountMap.get(o)));
                        }
                    }            
                }
            }
            
            try
            {
            
                oppty.StageName = [Select Id,Stats_Before_Convert__c from Lead where Id=:LeadId].Stats_Before_Convert__c;
               System.debug('-------44444444----- '+ oppty.StageName);
                Database.SaveResult SROppty = database.update(oppty);
                //for(Database.Error err: SR.getErrors())
                //{
                    //system.debug('Error --> ' + err);
                    //system.debug('Error getMessage --> ' + err.getMessage());
                    //system.debug('Error getStatusCode--> ' + err.getStatusCode());
                   // process any errors here 
            
                //}
            }
            catch(DMLException e)
            {
                 //ApexPages.addMessage(e);
            }
         

    }
    public pageReference ForceOpportunityCreation()
    {
        pageReference  p;
        List<Opportunity> o = new List<Opportunity>();

            /*if(convertedLead.IsConverted == TRUE && convertedLead.ConvertedOpportunityId == NULL){               
                o.add (new Opportunity(
                Name = convertedLead.Company,
                CloseDate = date.today()+90,
                AccountId = convertedLead.ConvertedAccountId,
                StageName = '1 - Qualification'));
                }
        */
        insert o;
        return p;
    }
    //This method is used to get the fields of an Object using Global Describe function from Salesforce.com
    public static List<String> getoDescribe(string selectedObject)
    {
        List<String> listObjectFields;
        listObjectFields =  new List<String>();
        Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();        
        Schema.sObjectType sObjType = globalDescription.get(selectedObject);        
        sObject sObjectToBind = sObjType.newSObject();
        Schema.DescribeSObjectResult r1 = sObjType.getDescribe();        
        Map<String , Schema.SObjectField> mapFieldList = r1.fields.getMap();
        for(Schema.SObjectField field : mapFieldList.values())
        {
                Schema.DescribeFieldResult fieldResult = field.getDescribe();
                //leave out the read only fields
                if(fieldResult.isUpdateable())
                {
                    listObjectFields.add(fieldResult.getName()); 
                }
        }
        return  (listObjectFields);              
    }

}